package com.xiaobai.common.utils.config.advice;


import com.xiaobai.common.utils.result.R;
import com.xiaobai.common.utils.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;
import java.util.List;

@ControllerAdvice
public class RespBodyAdvice implements ResponseBodyAdvice<Object> {
    @Autowired(
        required = false
    )
    private BodyAdviceSupport bodyAdviceSupport;

    public RespBodyAdvice() {
    }

    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        Method method = methodParameter.getMethod();
  //判断Natice注解是否在method方法上面
//        if (method.isAnnotationPresent(Native.class)) {
//            return false;
//        } else {
            Class<?> declaringClass = method.getDeclaringClass();
            Package aPackage = declaringClass.getPackage();
   //获取到RespBodyAdvice类
            Class scanClass = RespBodyAdvice.class;
            if (this.bodyAdviceSupport != null) {
                Object supports = this.bodyAdviceSupport.supports();
                if (supports != null) {
                    scanClass = supports.getClass();
                }
            }
            String[] packeges = scanClass.getPackage().getName().split("\\.");
            String rooPackage = packeges[0] + "." + packeges[1];
   //比对配置类的包名是否与接口的包名是否一致            
   return aPackage.getName().startsWith(rooPackage);
        }
//    }

    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
  //获取请求头当中feign字段的数据
        List<String> headers = serverHttpRequest.getHeaders().get("feign");
  //这个里面的Result类就是具体的返回实体类
        if (o instanceof Result) {
//            if (headers != null && "true".equals(headers.get(0))) {
//                throw new ServiceException(CommonErrorCode.FEIGN_ERROR);
//            } else {
                return o;
//            }
        } else {
            return headers != null && "true".equals(headers.get(0)) ? o : R.success(o);
        }
    }
}
